from django import http
from fdfs_client.client import Fdfs_client
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from goods.models import SPU, SPUSpecification, GoodsCategory, Brand
from meiduo_admin.serializers.spus import GoodsSimpleSerializer, GoodsSpecsSerializer, GoodsSerializer, \
    GoodsChannelCategoriesSerializer, GoodsBrandsSimpleSerializer, GoodsChannelCategoriessSerializer, \
    GoodsSpecssSerializer


class GoodsSimpleView(ListAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = GoodsSimpleSerializer
    queryset = SPU.objects.all()
    pagination_class = None


class GoodsSpecsView(ListAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = GoodsSpecsSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        return SPUSpecification.objects.filter(spu_id=pk)

    pagination_class = None


class GoodsView(ModelViewSet):
    permission_classes = [IsAdminUser]
    serializer_class = GoodsSerializer
    queryset = SPU.objects.all()

    lookup_value_regex = '\d+'


class GoodsImagesView(APIView):
    permission_classes = [IsAdminUser]
    lookup_value_regex = '\d+'

    def post(self, request):
        image_url = request.FILES['image']
        client = Fdfs_client('meiduo_mall/utils/fdfs/client.conf')
        res = client.upload_by_buffer(image_url.read())
        image = res.get('Remote file_id')
        image = 'http://192.168.150.141:8888/' + image
        return http.JsonResponse({'code': 1,
                                  'error': 'ok',
                                  'img_url': image})


class GoodsChannelCategoriesView(ListAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = GoodsChannelCategoriesSerializer
    queryset = GoodsCategory.objects.filter(parent=None)
    pagination_class = None


class GoodsBrandsSimpleView(ListAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = GoodsBrandsSimpleSerializer
    queryset = Brand.objects.all()
    pagination_class = None
    lookup_value_regex = '\d+'


class GoodsChannelCategoriessView(RetrieveAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = GoodsChannelCategoriessSerializer
    queryset = GoodsCategory.objects.all()
    pagination_class = None


class GoodsSpecssView(ModelViewSet):
    permission_classes = [IsAdminUser]
    serializer_class = GoodsSpecssSerializer
    queryset = SPUSpecification.objects.all()
